package com.rock.securityresearch.infracture

import cats.ApplicativeThrow
import com.rock.securityresearch.util.http.{Http, HttpResponse}
import cats.effect.Sync
import com.rock.securityresearch.util.JsonUtil
import org.typelevel.log4cats.Logger

import scala.util.Try

object Netease {

    import cats.syntax.all.toFunctorOps
    import cats.implicits.toFlatMapOps
    import io.circe.generic.auto.*
    import io.circe.parser.*

    def search[F[_] : Sync : Logger : ApplicativeThrow](word: String): F[List[SearchResultItem]] = {
        val resF = Http[F].get(s"https://quotes.money.163.com/stocksearch/json.do?type=&count=10&word=$word")
        for {
            res <- resF
            resBody <- ApplicativeThrow[F].fromTry(isOk(res))
            items <- ApplicativeThrow[F].fromEither(JsonUtil.fromJson[List[SearchResultItem]](resBody))
        } yield items
    }

    def isOk(res: HttpResponse): Try[String] = {
        if (!res.isOk) {
            Try {
                throw Exception(s"response is not ok: ${res.statusCode}")
            }
        } else if (!res.bodyAsString().startsWith("_ntes_stocksearch_callback(")) {
            Try {
                throw Exception(s"not startsWith _ntes_stocksearch_callback")
            }
        } else {
            Try(res.bodyAsString().replace("_ntes_stocksearch_callback(", "").dropRight(1))
        }
    }

}

case class SearchResultItem(code: String, name: String, spell: String, symbol: String, tag: String)